// import fs from 'fs';
import httpRuoter from './methods/http'
import pluginPrivate from './methods/plugin-private'
import openRuoter from './methods/open'
import callRuoter from './methods/call'
import { ObjToParam } from '../utils/base'

const createdRoute = (url, data = {}, type = 'xiavan', routes) => {
  url = url.replace(/^\s*|\s*$/g, "")
  if (Object.prototype.toString.call(data) != '[object Object]') {
    console.log('data is on object')
    return
  }
  if (!(/^.*:\/\/.*/.test(url))) {
    console.log('路由地址不合法  xxxx://')
    return
  }
  //判断http
  if (/^http[s]{0,1}:\/\//.test(url)) {
    httpRuoter(url)
    return
  }
  //判断直播
  if (/^plugin-private:\/\//.test(url)) {
    pluginPrivate(url)
    return
  }
  // 处理参数
  let option = ObjToParam(data)
  if (option) {
    url = url.indexOf('?') != -1 ? `${url}&${option}` : `${url}?${option}`
  }

  //判断是否内部路由
  if (new RegExp(`^${type}`).test(url)) {
    //判断open
    new RegExp(`^${type}:\/\/open\/`).test(url) && openRuoter(url, routes)
    //判断call
    new RegExp(`^${type}:\/\/call\/`).test(url) && callRuoter(url)

  } else { // 处理外部路由
    console.log('外部路由  ', url)
  }

}

class Router {
  constructor({ agreement = 'xiavan', routes = {} }) {
    this.agreement = agreement;
    this.routes = routes;
  }
  open(url, data) {
    createdRoute(url, data, this.agreement, this.routes)
  }

  back(number) {
    uni.navigateBack({
      delta: number || 1
    })
  }
}

Router.install = function (Vue, option) {
  Vue.prototype.$router = new Router(option)
}



export default Router
